package com.wenwan.manage.impl;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.fusesource.hawtbuf.BufferInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.image.ClientConfig;
import com.image.common_utils.CommonCodecUtils;
import com.image.exception.AbstractImageException;
import com.image.exception.UnknownException;
import com.image.sign.Credentials;
import com.wenwan.manage.mapper.RedisDao;
import com.wenwan.manage.pojo.Authentication;
import com.wenwan.manage.pojo.DataToObject;
import com.wenwan.manage.pojo.FaceLivegetfour;
import com.wenwan.manage.pojo.FaceLivegetfourResult;
import com.wenwan.manage.pojo.IdCardFaceFather;
import com.wenwan.manage.pojo.IdCardFaceFatherList;
import com.wenwan.manage.pojo.IdCardOppositeFather;
import com.wenwan.manage.pojo.IdCardOppositeFatherList;
import com.wenwan.manage.pojo.IdentityAuthentication;
import com.wenwan.manage.service.AuthenticationService;
import com.wenwan.manage.service.UserAuthenticationService;
import com.wenwan.manage.service.UserPhoneService;
import com.wenwan.manage.setting.RegExpSetting;
import com.wenwan.manage.setting.StatusSetting;
import com.wenwan.manage.setting.WxytSetting;
import com.wenwan.manage.util.Util;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

	@Override
	public Map<String, Object> checkIdCard(String userId, byte[] bytes, String originalFilename, Integer card_type,
			String token) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> faceLivegetfour(String userId, String token) {
		// TODO Auto-generated method stub
		// DataToObject<Object> dto = new DataToObject<Object>();
		Map<String, Object> dto = new HashMap<String, Object>();

		if (userId != null && !userId.matches(RegExpSetting.PARA_ID)) {
			dto.put("data", false);
			dto.put("msg", "userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.put("code", StatusSetting.CODE_10050);
			// dto.setData(false);
			// dto.setMsg("userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			// dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		if (token != null && !token.matches(RegExpSetting.PARA_ID)) {
			dto.put("data", false);
			dto.put("msg", "token" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.put("code", StatusSetting.CODE_10050);
			// dto.setData(false);
			// dto.setMsg("token" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			// dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		RedisDao redisDao = new RedisDao();
		// 审核标记缓存对象
		IdentityAuthentication identityAuthentication = redisDao.getIdentityAuthentication(token);
		System.out.println(4);
		System.out.println(identityAuthentication);
		// 审核标记是否存在
		if (identityAuthentication == null) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_1);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("审核标记已过期，请重新开始审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsStart()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_2);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("审核标记未开始，请重新开始审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsGetVerificationCode()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_3);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("请先获取手机验证码再验证");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsVerificationCodeSuccess()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_4);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("短信验证码不成功");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckIdCardFace()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_5);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证正面未审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckIdCardFaceSuccess()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_6);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证正面审核未通过，请重新审核身份证正面");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckOpposite()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_7);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证背面未审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckOppositeSuccess()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_8);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证背面审核未通过，请重新审核身份证正面");
			// dto.setCode("10030");
			return dto;
		}

		final String remote_url = "http://service.image.myqcloud.com/face/livegetfour";// 第三方服务器请求地址
		Credentials cred = new Credentials(WxytSetting.APPID, WxytSetting.SECRET_ID, WxytSetting.SECRET_KEY);
		ClientConfig clientConfig = new ClientConfig();
		String authorization = "";

		try {
			authorization = appSign(cred, WxytSetting.BUCKET_NAME, clientConfig.getSignExpired());
		} catch (AbstractImageException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		try {

			HttpPost httpPost = new HttpPost(remote_url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			httpPost.setHeader("Authorization", authorization);
			builder.addTextBody("appid", WxytSetting.APPID + "");// 类似浏览器表单提交，对应input的name和value
			// builder.addTextBody("bucket", "renzheng");// 类似浏览器表单提交，对应input的name和value
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);// 执行提交
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				// 将响应内容转换为字符串
				result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
				FaceLivegetfour faceLivegetfour = new Gson().fromJson(result, FaceLivegetfour.class);
				System.out.println(result);
				// 获取唇语验证码成功
				if (faceLivegetfour.getCode() == 0) {
					// 标记获取唇语验证码成功
					identityAuthentication.setIsGetFaceLivegetfour(true);
					// 标记唇语验证码
					identityAuthentication.setValidateData(faceLivegetfour.getData().getValidate_data());
					// identityAuthentication.setValidateData("0857");
					// 更新缓存
					redisDao.putIdentityAuthentication(identityAuthentication);

					// FaceLivegetfourData faceLivegetfourData = faceLivegetfour.getData();
					// faceLivegetfourData.setValidate_data("0857");

					dto.put("data", faceLivegetfour.getData());
					dto.put("msg", StatusSetting.MSG_200);
					dto.put("code", StatusSetting.CODE_200);
					return dto;
				} else {
					dto.put("data", faceLivegetfour.getData());
					dto.put("msg", faceLivegetfour.getCode() + "");
					dto.put("code", faceLivegetfour.getMessage());
					// dto.setData(faceLivegetfour.getData());
					// dto.setCode(faceLivegetfour.getCode() + "");
					// dto.setMsg(faceLivegetfour.getMessage());
					return dto;
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		dto.put("data", false);
		dto.put("msg", "未知错误");
		dto.put("code", "10000");
		// dto.setData("出错");
		// dto.setCode("10000");
		// dto.setMsg("未知错误");
		return dto;

	}

	@Autowired
	private UserPhoneService userPhoneService;

	@Override
	public Map<String, Object> faceLiveDetectFour2(String userId, String validate_data, byte[] bytes,
			String originalFilename, Boolean compare_flag, String seq, String token) {
		// TODO Auto-generated method stub
		// DataToObject<Object> dto = new DataToObject<Object>();
		Map<String, Object> dto = new HashMap<String, Object>();

		if (userId != null && !userId.matches(RegExpSetting.PARA_ID)) {
			dto.put("data", false);
			dto.put("msg", "userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.put("code", StatusSetting.CODE_10050);
			// dto.setData(false);
			// dto.setMsg("userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			// dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		if (token != null && !token.matches(RegExpSetting.PARA_ID)) {
			dto.put("data", false);
			dto.put("msg", "token" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.put("code", StatusSetting.CODE_10050);
			// dto.setData(false);
			// dto.setMsg("token" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			// dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		RedisDao redisDao = new RedisDao();
		// 审核标记缓存对象
		IdentityAuthentication identityAuthentication = redisDao.getIdentityAuthentication(token);
		System.out.println(5);
		System.out.println(identityAuthentication);
		// 审核标记是否存在
		if (identityAuthentication == null) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_1);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("审核标记已过期，请重新开始审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsStart()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_2);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("审核标记未开始，请重新开始审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsGetVerificationCode()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_3);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("请先获取手机验证码再验证");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsVerificationCodeSuccess()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_4);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("短信验证码不成功");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckIdCardFace()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_5);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证正面未审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckIdCardFaceSuccess()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_6);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证正面审核未通过，请重新审核身份证正面");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckOpposite()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_7);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证背面未审核");
			// dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckOppositeSuccess()) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_8);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg("身份证背面审核未通过，请重新审核身份证正面");
			// dto.setCode("10030");
			return dto;
		}

		// 判断唇语验证码前后台是否一致
		if (!validate_data.equals(identityAuthentication.getValidateData())) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10030_11);
			dto.put("code", StatusSetting.CODE_10030);
			// dto.setData(false);
			// dto.setMsg(StatusSetting.MSG_10030_11);
			// dto.setCode(StatusSetting.CODE_10030);
			return dto;
		}

		final String remote_url = "http://service.image.myqcloud.com/face/livedetectfour";// 第三方服务器请求地址

		Credentials cred = new Credentials(WxytSetting.APPID, WxytSetting.SECRET_ID, WxytSetting.SECRET_KEY);
		ClientConfig clientConfig = new ClientConfig();
		String authorization = "";

		try {

			authorization = appSign(cred, WxytSetting.BUCKET_NAME, clientConfig.getSignExpired());
			System.out.println(authorization);

		} catch (AbstractImageException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(remote_url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			httpPost.setHeader("Authorization", authorization);
			// httpPost.setHeader("Content-Type", "multipart/form-data");
			builder.addTextBody("appid", WxytSetting.APPID + "");// 类似浏览器表单提交，对应input的name和value
			builder.addTextBody("validate_data", validate_data);
			builder.addTextBody("compare_flag", "false");

			builder.addBinaryBody("video", new BufferInputStream(bytes), ContentType.MULTIPART_FORM_DATA, "953392.mp4");

			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);// 执行提交
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				// 将响应内容转换为字符串
				result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
				System.out.println(result);
				FaceLivegetfourResult faceLivegetfourResult = new Gson().fromJson(result, FaceLivegetfourResult.class);

				if (faceLivegetfourResult.getCode() == 0) {

					if (faceLivegetfourResult.getData().getLive_status() == 0) {// 活体检测成功

						// 标记已进行活体检测
						identityAuthentication.setIsFaceLiveDetectFour(true);
						// 标记活体检测通过审核
						identityAuthentication.setIsFaceLiveDetectFourSuccess(true);
						// 更新缓存
						redisDao.putIdentityAuthentication(identityAuthentication);
						// 保存到数据库
						// String userId, String realName, String birthday, String address,
						// String identity, String sex, String nation, String office, String validity,
						// String phone
						// 获取认证信息
						Authentication authentication = identityAuthentication.getAuthentication();

						Boolean success = (Boolean) userAuthenticationService.create(userId,
								authentication.getRealName(), authentication.getBirthday(), authentication.getAddress(),
								authentication.getIdentity(), authentication.getSex(), authentication.getNation(),
								authentication.getOffice(), authentication.getValidity(), authentication.getPhone())
								.get("data");

						userPhoneService.create(authentication.getPhone(), userId);

						if (success) {
							// dto.setData(true);
							dto.put("data", true);
							dto.put("msg", StatusSetting.MSG_200);
							dto.put("code", StatusSetting.CODE_200);
							return dto;
						} else {
							dto.put("data", false);
							dto.put("msg", "认证失败");
							dto.put("code", "10020");
							// dto.setData(false);
							// dto.setMsg("认证失败");
							// dto.setCode("10020");
							return dto;
						}

					} else {// 活体检测失败

						// 标记已进行活体检测
						identityAuthentication.setIsFaceLiveDetectFour(true);
						// 标记活体检测审核失败
						identityAuthentication.setIsFaceLiveDetectFourSuccess(false);
						// 更新缓存
						redisDao.putIdentityAuthentication(identityAuthentication);

						// dto.setData(false);
						// dto.setCode(faceLivegetfourResult.getData().getLive_status() + "");
						// dto.setMsg(faceLivegetfourResult.getData().getLive_msg());
						dto.put("data", false);
						dto.put("msg", faceLivegetfourResult.getData().getLive_msg());
						dto.put("code", faceLivegetfourResult.getData().getLive_status() + "");
						return dto;

					}

				} else {

					dto.put("data", false);
					dto.put("msg", faceLivegetfourResult.getData().getLive_msg());
					dto.put("code", faceLivegetfourResult.getData().getLive_status() + "");
					// dto.setData(false);
					// dto.setCode("");
					// dto.setMsg(faceLivegetfourResult.getData().getLive_msg());
					return dto;

				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		dto.put("data", false);
		dto.put("msg", "未知错误");
		dto.put("code", "10000");
		// dto.setData(false);
		// dto.setCode("10000");
		// dto.setMsg("未知错误");
		return dto;
	}

	@Autowired
	private UserAuthenticationService userAuthenticationService;

	private Map<String, Object> isAuthentication(String id) {
		Map<String, Object> dto = userAuthenticationService.selectOneById(id);
		return dto;
	}

	@Override
	public Map<String, Object> startAuthentication(String userId) {
		// TODO Auto-generated method stub
		// DataToObject<Object> dto = new DataToObject<Object>();
		Map<String, Object> dto = new HashMap<String, Object>();
		Boolean isAuthentication = (Boolean) isAuthentication(userId).get("data");

		if (userId != null && !userId.matches(RegExpSetting.PARA_ID)) {
			dto.put("data", false);
			dto.put("msg", "userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.put("code", StatusSetting.CODE_10050);
			// dto.setData(false);
			// dto.setMsg("userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			// dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		if (isAuthentication) {
			dto.put("data", false);
			dto.put("msg", StatusSetting.MSG_10050_THE_USER_IS_AUTHENTICATION);
			dto.put("code", StatusSetting.CODE_10050);
			// dto.setData(false);
			// dto.setMsg(StatusSetting.MSG_10050_THE_USER_IS_AUTHENTICATION);
			// dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		RedisDao redisDao = new RedisDao();
		IdentityAuthentication identityAuthentication = new IdentityAuthentication();
		String id = Util.UUID();

		identityAuthentication.setId(id);
		identityAuthentication.setIsStart(true);// 已开始
		identityAuthentication.setIsCheckIdCardFace(false);// 是否检测了身份证正面
		identityAuthentication.setIsCheckIdCardFaceSuccess(false);// 身份证正面检测是否成功
		identityAuthentication.setIsCheckOpposite(false);// 是否检测了身份证背面
		identityAuthentication.setIsCheckOppositeSuccess(false);// 身份证背面检测是否成功
		identityAuthentication.setIsGetFaceLivegetfour(false);// 是否获取了唇语验证码
		identityAuthentication.setValidateData(null);// 获取的唇语验证码
		identityAuthentication.setIsFaceLiveDetectFour(false);// 是否进行了活体检测
		identityAuthentication.setIsFaceLiveDetectFourSuccess(false);// 活体检测是否成功
		identityAuthentication.setUserId(userId);// 被检测的用户
		identityAuthentication.setIsGetVerificationCode(false);// 是否获得了手机验证码
		identityAuthentication.setIsVerificationCodeSuccess(false);// 手机验证码是否验证成功
		identityAuthentication.setIsAuthentication(false);// 用户是否已认证
		identityAuthentication.setIsAuthenticationSuccess(false);// 用户是否认证通过

		identityAuthentication.setAuthentication(new Authentication());// 认证信息

		redisDao.putIdentityAuthentication(identityAuthentication);

		// dto.setData(id);
		dto.put("data", id);
		dto.put("msg", StatusSetting.MSG_200);
		dto.put("code", StatusSetting.CODE_200);
		return dto;
	}

	public static DataToObject<Object> checkIdCard(String userId, MultipartFile file, Integer card_type, String token) {

		DataToObject<Object> dto = new DataToObject<Object>();

		if (userId != null && !userId.matches(RegExpSetting.PARA_ID)) {
			dto.setData(false);
			dto.setMsg("userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		if (token != null && !token.matches(RegExpSetting.PARA_ID)) {
			dto.setData(false);
			dto.setMsg("token" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
			dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		if (card_type != null && card_type < 0) {
			dto.setData(false);
			dto.setMsg("card_type" + StatusSetting.MSG_10050_IS_CAN_NOT_LESS_ZERO);
			dto.setCode(StatusSetting.CODE_10050);
			return dto;
		}

		final String remote_url = "http://recognition.image.myqcloud.com/ocr/idcard";// 第三方服务器请求地址

		Credentials cred = new Credentials(WxytSetting.APPID, WxytSetting.SECRET_ID, WxytSetting.SECRET_KEY);
		ClientConfig clientConfig = new ClientConfig();
		String authorization = "";

		try {

			authorization = appSign(cred, WxytSetting.BUCKET_NAME, clientConfig.getSignExpired());

		} catch (AbstractImageException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		try {
			String fileName = file.getOriginalFilename();
			// String end = fileName.substring(fileName.indexOf(".") + 1,
			// fileName.length());

			HttpPost httpPost = new HttpPost(remote_url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			httpPost.setHeader("Authorization", authorization);

			builder.addBinaryBody("image", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流

			builder.addTextBody("appid", 1255370023 + "");// 类似浏览器表单提交，对应input的name和value
			builder.addTextBody("card_type", card_type + "");
			builder.addTextBody("bucket", "renzheng");// 类似浏览器表单提交，对应input的name和value
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);// 执行提交
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				// 将响应内容转换为字符串
				result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		Gson gson = new Gson();
		if (card_type == 0) {
			IdCardFaceFatherList idCardFaceFatherList = gson.fromJson(result, IdCardFaceFatherList.class);
			if (idCardFaceFatherList.getResult_list().size() > 0) {
				if (idCardFaceFatherList.getResult_list().get(0).getCode() == 0) {

					IdCardFaceFather idCardFaceFather = idCardFaceFatherList.getResult_list().get(0);
					// 验证身份证正面
					dto = adopt(idCardFaceFather, token);
					return dto;

				} else {
					dto.setData(false);
					dto.setCode(idCardFaceFatherList.getResult_list().get(0).getCode() + "");
					dto.setMsg(idCardFaceFatherList.getResult_list().get(0).getMessage());
					return dto;
				}
			} else {
				dto.setData(false);
			}
			dto.setData(idCardFaceFatherList);
		} else if (card_type == 1) {
			IdCardOppositeFatherList idCardOppositeFatherList = gson.fromJson(result, IdCardOppositeFatherList.class);
			if (idCardOppositeFatherList.getResult_list().size() > 0) {
				if (idCardOppositeFatherList.getResult_list().get(0).getCode() == 0) {

					IdCardOppositeFather idCardOppositeFather = idCardOppositeFatherList.getResult_list().get(0);
					// 验证身份证背面
					dto = adopt(idCardOppositeFather, token);
					return dto;

				} else {
					dto.setData(false);
					dto.setCode(idCardOppositeFatherList.getResult_list().get(0).getCode() + "");
					dto.setMsg(idCardOppositeFatherList.getResult_list().get(0).getMessage());
					return dto;
				}
			}
			dto.setData(idCardOppositeFatherList);
		} else {
			dto.setData(false);
			dto.setCode(StatusSetting.CODE_10003);
			dto.setMsg(StatusSetting.MSG_10003);
		}
		return dto;
	}

	private static DataToObject<Object> adopt(IdCardOppositeFather idCardOppositeFather, String token) {
		// TODO Auto-generated method stub
		DataToObject<Object> dto = new DataToObject<Object>();
		DataToObject<Boolean> dtob = new DataToObject<Boolean>();

		// 验证缓存
		RedisDao redisDao = new RedisDao();
		IdentityAuthentication identityAuthentication = redisDao.getIdentityAuthentication(token);

		// 审核标记是否存在
		if (identityAuthentication == null) {
			dto.setData(false);
			dto.setMsg("审核标记不存在，请重新开始审核");
			dto.setCode("10030");
			return dto;
		}

		if (identityAuthentication != null && !identityAuthentication.getIsStart()) {
			dto.setData(false);
			dto.setCode("10020");
			dto.setMsg("此审核未开始");
			return dto;
		}

		if (!identityAuthentication.getIsGetVerificationCode()) {
			dto.setData(false);
			dto.setMsg("请先获取手机验证码再验证");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsVerificationCodeSuccess()) {
			dto.setData(false);
			dto.setMsg("短信验证码不成功");
			dto.setCode("10030");
			return dto;
		}

		// 身份证背面已审核
		identityAuthentication.setIsCheckOpposite(true);

		List<Integer> authority_confidence_all = idCardOppositeFather.getData().getAuthority_confidence_all();
		dtob = adopt(authority_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}
		List<Integer> valid_date_confidence_all = idCardOppositeFather.getData().getValid_date_confidence_all();
		dtob = adopt(valid_date_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		// 身份证背面审核成功
		identityAuthentication.setIsCheckOppositeSuccess(true);

		// 获取认证信息
		Authentication authentication = identityAuthentication.getAuthentication();

		// 更新认证信息
		authentication.setOffice(idCardOppositeFather.getData().getAuthority());
		authentication.setValidity(idCardOppositeFather.getData().getValid_date());

		// 更新认证流程
		identityAuthentication.setAuthentication(authentication);

		// 更新缓存
		redisDao.putIdentityAuthentication(identityAuthentication);

		dto.setData(idCardOppositeFather.getData());
		return dto;
	}

	private static DataToObject<Boolean> adopt(List<Integer> list) {
		DataToObject<Boolean> dto = new DataToObject<Boolean>();
		for (Integer item : list) {
			if (item < 75) {
				dto.setData(false);
				dto.setCode(StatusSetting.CODE_10010);
				dto.setMsg(StatusSetting.MSG_10010);
				return dto;
			}
		}
		dto.setData(true);
		return dto;
	}

	private static DataToObject<Object> adopt(IdCardFaceFather idCardFaceFather, String token) {
		// TODO Auto-generated method stub
		DataToObject<Object> dto = new DataToObject<Object>();
		DataToObject<Boolean> dtob = new DataToObject<Boolean>();

		// 验证缓存
		RedisDao redisDao = new RedisDao();
		IdentityAuthentication identityAuthentication = redisDao.getIdentityAuthentication(token);
		// 审核标记是否存在
		if (identityAuthentication == null) {
			dto.setData(false);
			dto.setMsg("审核标记不存在，请重新开始审核");
			dto.setCode("10030");
			return dto;
		}

		if (identityAuthentication != null && !identityAuthentication.getIsStart()) {
			dto.setData(false);
			dto.setCode("10020");
			dto.setMsg("此审核未开始");
			return dto;
		}

		if (!identityAuthentication.getIsGetVerificationCode()) {
			dto.setData(false);
			dto.setMsg("请先获取手机验证码再验证");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsVerificationCodeSuccess()) {
			dto.setData(false);
			dto.setMsg("短信验证码不成功");
			dto.setCode("10030");
			return dto;
		}

		// 身份证正面已审核
		identityAuthentication.setIsCheckIdCardFace(true);

		List<Integer> address_confidence_all = idCardFaceFather.getData().getAddress_confidence_all();

		List<Integer> birth_confidence_all = idCardFaceFather.getData().getBirth_confidence_all();

		List<Integer> id_confidence_all = idCardFaceFather.getData().getId_confidence_all();

		List<Integer> name_confidence_all = idCardFaceFather.getData().getName_confidence_all();

		List<Integer> nation_confidence_all = idCardFaceFather.getData().getNation_confidence_all();

		List<Integer> sex_confidence_all = idCardFaceFather.getData().getSex_confidence_all();

		dtob = adopt(address_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		dtob = adopt(birth_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		dtob = adopt(id_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		dtob = adopt(name_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		dtob = adopt(nation_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		dtob = adopt(sex_confidence_all);
		if (!dtob.getData()) {

			// 更新缓存
			redisDao.putIdentityAuthentication(identityAuthentication);

			dto.setData(false);
			dto.setCode(dtob.getCode());
			dto.setMsg(dtob.getMsg());
			return dto;
		}

		// 审核通过
		identityAuthentication.setIsCheckIdCardFaceSuccess(true);

		// 获取认证信息
		Authentication authentication = identityAuthentication.getAuthentication();
		// 修改认证信息
		authentication.setRealName(idCardFaceFather.getData().getName());
		authentication.setNation(idCardFaceFather.getData().getNation());
		authentication.setSex(idCardFaceFather.getData().getSex());
		authentication.setAddress(idCardFaceFather.getData().getAddress());
		authentication.setBirthday(idCardFaceFather.getData().getBirth());
		authentication.setValidity(idCardFaceFather.getData().getId());

		// 更新认证流程
		identityAuthentication.setAuthentication(authentication);

		// 更新缓存
		redisDao.putIdentityAuthentication(identityAuthentication);

		dto.setData(idCardFaceFather.getData());
		return dto;
	}

	public static String appSign(Credentials cred, String bucketName, long expired) throws AbstractImageException {
		int appId = cred.getAppId();
		String secretId = cred.getSecretId();
		String secretKey = cred.getSecretKey();
		long now = System.currentTimeMillis() / 1000;
		// int rdm = Math.abs(new Random().nextInt());
		String plainText = String.format("a=%d&b=%s&k=%s&t=%d&e=%d", appId, bucketName, secretId, now, now + expired);
		byte[] hmacDigest;
		try {
			hmacDigest = CommonCodecUtils.HmacSha1(plainText, secretKey);
		} catch (Exception e) {
			throw new UnknownException(e.getMessage());
		}
		byte[] signContent = new byte[hmacDigest.length + plainText.getBytes().length];
		System.arraycopy(hmacDigest, 0, signContent, 0, hmacDigest.length);
		System.arraycopy(plainText.getBytes(), 0, signContent, hmacDigest.length, plainText.getBytes().length);
		// System.out.println(CommonCodecUtils.Base64Encode(signContent));
		return CommonCodecUtils.Base64Encode(signContent);
	}

	// public static DataToObject<Object> faceLivegetfour(String userId, String
	// token) {
	// // TODO Auto-generated method stub
	//
	// DataToObject<Object> dto = new DataToObject<Object>();
	//
	// if (userId != null && !userId.matches(RegExpSetting.PARA_ID)) {
	// dto.setData(false);
	// dto.setMsg("userId" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
	// dto.setCode(StatusSetting.CODE_10050);
	// return dto;
	// }
	//
	// if (token != null && !token.matches(RegExpSetting.PARA_ID)) {
	// dto.setData(false);
	// dto.setMsg("token" + StatusSetting.MSG_10050_FORMAT_IS_MISTAKE);
	// dto.setCode(StatusSetting.CODE_10050);
	// return dto;
	// }
	//
	// RedisDao redisDao = new RedisDao();
	// // 审核标记缓存对象
	// IdentityAuthentication identityAuthentication =
	// redisDao.getIdentityAuthentication(token);
	// System.out.println(4);
	// System.out.println(identityAuthentication);
	// // 审核标记是否存在
	// if (identityAuthentication == null) {
	// dto.setData(false);
	// dto.setMsg("审核标记已过期，请重新开始审核");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsStart()) {
	// dto.setData(false);
	// dto.setMsg("审核标记未开始，请重新开始审核");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsGetVerificationCode()) {
	// dto.setData(false);
	// dto.setMsg("请先获取手机验证码再验证");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsVerificationCodeSuccess()) {
	// dto.setData(false);
	// dto.setMsg("短信验证码不成功");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsCheckIdCardFace()) {
	// dto.setData(false);
	// dto.setMsg("身份证正面未审核");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsCheckIdCardFaceSuccess()) {
	// dto.setData(false);
	// dto.setMsg("身份证正面审核未通过，请重新审核身份证正面");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsCheckOpposite()) {
	// dto.setData(false);
	// dto.setMsg("身份证背面未审核");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// if (!identityAuthentication.getIsCheckOppositeSuccess()) {
	// dto.setData(false);
	// dto.setMsg("身份证背面审核未通过，请重新审核身份证正面");
	// dto.setCode("10030");
	// return dto;
	// }
	//
	// final String remote_url =
	// "http://service.image.myqcloud.com/face/livegetfour";// 第三方服务器请求地址
	// Credentials cred = new Credentials(WxytSetting.APPID, WxytSetting.SECRET_ID,
	// WxytSetting.SECRET_KEY);
	// ClientConfig clientConfig = new ClientConfig();
	// String authorization = "";
	//
	// try {
	// authorization = appSign(cred, WxytSetting.BUCKET_NAME,
	// clientConfig.getSignExpired());
	// } catch (AbstractImageException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	//
	// CloseableHttpClient httpClient = HttpClients.createDefault();
	// String result = "";
	// try {
	//
	// HttpPost httpPost = new HttpPost(remote_url);
	// MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	// httpPost.setHeader("Authorization", authorization);
	// builder.addTextBody("appid", WxytSetting.APPID + "");//
	// 类似浏览器表单提交，对应input的name和value
	// // builder.addTextBody("bucket", "renzheng");// 类似浏览器表单提交，对应input的name和value
	// HttpEntity entity = builder.build();
	// httpPost.setEntity(entity);
	// HttpResponse response = httpClient.execute(httpPost);// 执行提交
	// HttpEntity responseEntity = response.getEntity();
	// if (responseEntity != null) {
	// // 将响应内容转换为字符串
	// result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
	// FaceLivegetfour faceLivegetfour = new Gson().fromJson(result,
	// FaceLivegetfour.class);
	// System.out.println(result);
	// // 获取唇语验证码成功
	// if (faceLivegetfour.getCode() == 0) {
	// // 标记获取唇语验证码成功
	// identityAuthentication.setIsGetFaceLivegetfour(true);
	// // 标记唇语验证码
	// identityAuthentication.setValidateData(faceLivegetfour.getData().getValidate_data());
	// // identityAuthentication.setValidateData("0857");
	// // 更新缓存
	// redisDao.putIdentityAuthentication(identityAuthentication);
	//
	// // FaceLivegetfourData faceLivegetfourData = faceLivegetfour.getData();
	// // faceLivegetfourData.setValidate_data("0857");
	//
	// dto.setData(faceLivegetfour.getData());
	// return dto;
	// } else {
	// dto.setData(faceLivegetfour.getData());
	// dto.setCode(faceLivegetfour.getCode() + "");
	// dto.setMsg(faceLivegetfour.getMessage());
	// return dto;
	// }
	// }
	//
	// } catch (IOException e) {
	// e.printStackTrace();
	// } catch (Exception e) {
	// e.printStackTrace();
	// } finally {
	// try {
	// httpClient.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// dto.setData("出错");
	// dto.setCode("10000");
	// dto.setMsg("未知错误");
	// return dto;
	// }

	public static DataToObject<Object> faceLiveDetectFour(String userId, String validate_data, MultipartFile video,
			Boolean compare_flag, String seq, String token) {
		// TODO Auto-generated method stub
		DataToObject<Object> dto = new DataToObject<Object>();

		RedisDao redisDao = new RedisDao();
		// 审核标记缓存对象
		IdentityAuthentication identityAuthentication = redisDao.getIdentityAuthentication(token);
		System.out.println(5);
		System.out.println(identityAuthentication);
		// 审核标记是否存在
		if (identityAuthentication == null) {
			dto.setData(false);
			dto.setMsg("审核标记已过期，请重新开始审核");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsStart()) {
			dto.setData(false);
			dto.setMsg("审核标记未开始，请重新开始审核");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsGetVerificationCode()) {
			dto.setData(false);
			dto.setMsg("请先获取手机验证码再验证");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsVerificationCodeSuccess()) {
			dto.setData(false);
			dto.setMsg("短信验证码不成功");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckIdCardFace()) {
			dto.setData(false);
			dto.setMsg("身份证正面未审核");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckIdCardFaceSuccess()) {
			dto.setData(false);
			dto.setMsg("身份证正面审核未通过，请重新审核身份证正面");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckOpposite()) {
			dto.setData(false);
			dto.setMsg("身份证背面未审核");
			dto.setCode("10030");
			return dto;
		}

		if (!identityAuthentication.getIsCheckOppositeSuccess()) {
			dto.setData(false);
			dto.setMsg("身份证背面审核未通过，请重新审核身份证正面");
			dto.setCode("10030");
			return dto;
		}

		// 判断唇语验证码前后台是否一致
		if (!validate_data.equals(identityAuthentication.getValidateData())) {
			dto.setData(false);
			dto.setMsg("唇语验证码与后台的不一致");
			dto.setCode("10030");
			return dto;
		}

		final String remote_url = "http://service.image.myqcloud.com/face/livedetectfour";// 第三方服务器请求地址

		Credentials cred = new Credentials(WxytSetting.APPID, WxytSetting.SECRET_ID, WxytSetting.SECRET_KEY);
		ClientConfig clientConfig = new ClientConfig();
		String authorization = "";

		try {

			authorization = appSign(cred, WxytSetting.BUCKET_NAME, clientConfig.getSignExpired());
			System.out.println(authorization);

		} catch (AbstractImageException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(remote_url);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			httpPost.setHeader("Authorization", authorization);
			// httpPost.setHeader("Content-Type", "multipart/form-data");
			builder.addTextBody("appid", WxytSetting.APPID + "");// 类似浏览器表单提交，对应input的name和value
			builder.addTextBody("validate_data", validate_data);
			builder.addTextBody("compare_flag", "false");

			builder.addBinaryBody("video", video.getInputStream(), ContentType.MULTIPART_FORM_DATA, "953392.mp4");

			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);// 执行提交
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				// 将响应内容转换为字符串
				result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
				System.out.println(result);
				FaceLivegetfourResult faceLivegetfourResult = new Gson().fromJson(result, FaceLivegetfourResult.class);

				if (faceLivegetfourResult.getCode() == 0) {

					if (faceLivegetfourResult.getData().getLive_status() == 0) {// 活体检测成功

						// 标记已进行活体检测
						identityAuthentication.setIsFaceLiveDetectFour(true);
						// 标记活体检测通过审核
						identityAuthentication.setIsFaceLiveDetectFourSuccess(true);
						// 更新缓存
						redisDao.putIdentityAuthentication(identityAuthentication);
						// 保存到数据库
						// userAuthenticationService.create(userId);

						dto.setData(true);
						return dto;

					} else {// 活体检测失败

						// 标记已进行活体检测
						identityAuthentication.setIsFaceLiveDetectFour(true);
						// 标记活体检测审核失败
						identityAuthentication.setIsFaceLiveDetectFourSuccess(false);
						// 更新缓存
						redisDao.putIdentityAuthentication(identityAuthentication);

						dto.setData(false);
						dto.setCode(faceLivegetfourResult.getData().getLive_status() + "");
						dto.setMsg(faceLivegetfourResult.getData().getLive_msg());
						return dto;
					}

				} else {

					dto.setData(false);
					dto.setCode("");
					dto.setMsg(faceLivegetfourResult.getData().getLive_msg());
					return dto;

				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		dto.setData("未知错误");
		dto.setCode("10000");
		dto.setMsg("未知错误");
		return dto;
	}

	// 开始活体检测
	// public static DataToObject<Object> startAuthentication(String userId) {
	// // TODO Auto-generated method stub
	// DataToObject<Object> dto = new DataToObject<Object>();
	// RedisDao redisDao = new RedisDao();
	// IdentityAuthentication identityAuthentication = new IdentityAuthentication();
	// String id = Util.UUID();
	//
	// identityAuthentication.setId(id);
	// identityAuthentication.setIsStart(true);// 已开始
	// identityAuthentication.setIsCheckIdCardFace(false);// 是否检测了身份证正面
	// identityAuthentication.setIsCheckIdCardFaceSuccess(false);// 身份证正面检测是否成功
	// identityAuthentication.setIsCheckOpposite(false);// 是否检测了身份证背面
	// identityAuthentication.setIsCheckOppositeSuccess(false);// 身份证背面检测是否成功
	// identityAuthentication.setIsGetFaceLivegetfour(false);// 是否获取了唇语验证码
	// identityAuthentication.setValidateData(null);// 获取的唇语验证码
	// identityAuthentication.setIsFaceLiveDetectFour(false);// 是否进行了活体检测
	// identityAuthentication.setIsFaceLiveDetectFourSuccess(false);// 活体检测是否成功
	// identityAuthentication.setUserId(userId);// 被检测的用户
	// identityAuthentication.setIsGetVerificationCode(false);// 是否获得了手机验证码
	// identityAuthentication.setIsVerificationCodeSuccess(false);// 手机验证码是否验证成功
	// identityAuthentication.setIsAuthentication(false);// 用户是否已认证
	// identityAuthentication.setIsAuthenticationSuccess(false);// 用户是否认证通过
	//
	// identityAuthentication.setAuthentication(new Authentication());// 认证信息
	//
	// redisDao.putIdentityAuthentication(identityAuthentication);
	//
	// dto.setData(id);
	// return dto;
	// }

}
